<template lang="pug">
  LayoutMain.dashboard-history
    div.dashboard-form(slot="form")
      .dashboard-form-options
        DashboardTarget(v-model="target",:targetList="targetList")
        DashboardInterval(v-show="useInterval",v-model="interval")
      DashboardDatePicker.el-date-editor-xxs(v-model="timeRange")
    DashboardChart(
      slot="chart"
      v-if="target!==''"
      :interval="interval"
      :target="target"
      :parameterList="parameterList"
      :devicesData="devicesData"
      @highLightTable="highLightTable")
    DashboardInfo(
      v-if="target!==''"
      slot="datatable"
      ref="info"
      :target="target"
      :parameterList="parameterList"
      :devicesData="devicesData"
      :currentDevicesTime="currentDevicesTime"
      :timeRange="timeRange"
      :interval="interval")
</template>

<script >
/**
 * @name Dashboard 历史数据页面
 * @author 陈可嘉
 * @description 各种指标历史数据的展示
 * @update linmn
 * @description 点击坐标跳转到历史数据页面
 */
// import testData from './Chart/data.js'
// import { uniq } from 'lodash'
import LayoutMain from '@/containers/Common/LayoutMain'
import DashboardTarget from './Form/Target'
import DashboardInterval from './Form/Interval'
import DashboardDatePicker from './Form/DatePicker'
import DashboardChart from './Chart'
import DashboardInfo from './Info'
import { device } from './device'
export default {
  name: 'DashboardHistory',
  components: {
    LayoutMain,
    DashboardTarget,
    DashboardInterval,
    DashboardDatePicker,
    DashboardChart,
    DashboardInfo
  },
  props: {
    devices: {
      type: Array,
      default: () => ([])
    }
  },
  data () {
    return {
      device,
      devicesType: '',
      // 当前选择列表
      targetList: [],
      target: '',
      // 指标列表
      parameterList: [],
      // 请求返回的设备数据，包含历史数据
      devicesData: [],
      // 请求返回的设备数据，包含历史数据
      currentDevicesTime: 0,
      interval: 'HOUR',
      timeRange: [this.$moment().subtract(6, 'days').startOf('day').format('x'), this.$moment().endOf('day').format('x')],
      isRequesting: false
    }
  },
  computed: {
    useInterval () {
      // 判断是否有需要使用步长，暂时有计算步长的只有“用水量”这个指标
      return this.target === 'waterQuantity'
    }
  },
  watch: {
    devices: {
      handler (data) {
        this.renderDevices()
      },
      immediate: true
    },
    timeRange: {
      handler (data) {
        this.getDevicesHistory()
      },
      deep: true
    },
    interval (val) {
      this.getDevicesHistory()
    },
    devicesType () {
      this.changeTargetList(this.parameterList)
    },
    target (val, old) {
      // 当为用水量时重新请求数据，或者用水量切换成其它时
      if (val === 'waterQuantity' || old === 'waterQuantity') {
        this.interval = 'HOUR'
        this.timeRange = [this.$moment().subtract(6, 'days').startOf('day').format('x'), this.$moment().endOf('day').format('x')]
      }
    }
  },
  methods: {
    renderDevices () {
      // 当前没选择设备时，不进行请求
      if (!this.devices.length) {
        return false
      }
      // 判断是否选择了不同类型的设备
      // const devicesTypes = uniq(this.devices.map(({deviceName}) => deviceName))
      // if (devicesTypes.length > 1) {
      //   this.$message({
      //     message: '请选择同一种类型的设备做对比',
      //     type: 'warning'
      //   })
      //   return false
      // }
      // 单设备刷新页面操作
      this.target = '' // 重置target
      this.timeRange = [this.$moment().subtract(6, 'days').startOf('day').format('x'), this.$moment().endOf('day').format('x')] // 重置时间
      this.devicesType = this.devices[0].deviceName
      // console.log('刷新页面改变发起请求')
      this.getDevicesHistory()
    },
    changeTargetList (data) {
      const device = this.device[this.devicesType]
      this.targetList = device && device.targetList ? device.targetList : data
      if (this.target !== 'waterQuantity') {
        this.target = this.targetList[0].value
      }
    },
    paramsFormat () {
      // 判断是用水量，请求的路径会不同
      const url = this.target === 'waterQuantity' ? '/pn/monitor/device/waterQuantity' : '/pn/monitor/device/historySearch'
      // 如果有加入步长，就把步长传入请求
      const intervalType = this.useInterval ? { intervalType: this.interval } : {}
      const deviceIds = this.devices.map(({siteId}) => siteId).join(',')
      const params = {
        'startTime': this.timeRange[0],
        'endTime': this.timeRange[1],
        ids: deviceIds,
        ...intervalType
      }
      return {
        url,
        params
      }
    },
    getDevicesHistory () {
      // 判断是否在请求中
      // console.log('请求状态', this.isRequesting)
      if (!this.isRequesting) {
        const loader = this.$loading() // 大loading
        const params = this.paramsFormat()
        this.isRequesting = true
        this.$get(params).then((data) => {
        // const data = testData.data
          loader.close()
          this.isRequesting = false
          if (!data.data) return
          if (data.target) {
            this.parameterList = data.target.map((item) => {
              return {
                ...item,
                value: item.mark
              }
            })
          } else {
            this.parameterList = [{
              mark: 'waterQuantity',
              label: '用水量',
              unit: 'm³'
            }]
          }
          this.changeTargetList(this.parameterList)
          // 待页面渲染完再赋值
          this.$nextTick(() => {
            this.devicesData = data.data.map(item => {
              return {
                ...item,
                data: item.data ? item.data.sort((a, b) => a.recordTime - b.recordTime) : []
              }
            })
          })
        })
      }
    },
    highLightTable (data) {
      console.log('history', data)
      this.$refs.info.highLightTable(data)
    }
  }
}
</script>

<style lang="sass" scoped>
.dashboard-form
  display: flex
  align-items: center
  justify-content: space-between
  padding: 0 10px
  height: 100%
</style>
